import dayjs from 'dayjs'
Page({
  data: {
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    houseLayerVisible: false,
    repairLayerVisible: false,
    dateLayerVisible: false,

    houseList: [],
    houseItem: {},
    repairList: [],
    repairItem: {},
    mobile: '',
    appointment: '', // 2022-10-01
    description: '',
    attachment: [],
  },
  onLoad({id}) {
    if(id) {
      this.getDetailInEdit(id)
    }
    this.getHouse()
    this.getRepaireList()
  },
  async getDetailInEdit(id) {
    wx.setNavigationBarTitle({
      title: '编辑报修信息',
    })
    const res = await wx.http.get(`/repair/${id}`)
    this.setData(Object.assign({}, {...res.data}, {
      houseItem: {id: res.data.houseId, name: res.data.houseInfo},
      repairItem: { id: res.data.repairItemId, name: res.data.repairItemName}
    }))
  },
  // 报修房屋2个函数
  async getHouse() {
    // 如果在工作里面，我们访问的接口没有数据，那么就要后端帮我添加几条假数据
    const res = await wx.http.get('/room')
    // 后端服务区返回的数据有点多，setData最大只能设置1MB的数据，我们在平时设置的时候，数据越小越好，一般会将服务器返回的数据加工处理以下
    // const houseList = res.data.map(item => ({ id: item.id, name: item.point}))
    const houseList = res.data.map(item => {
      return { id: item.id, name: item.point}
    })
    this.setData({
      houseList
    })
  },
  houseSelect(e) {
    this.setData({
      houseItem: e.detail
    })
  },
  // 维修项目的两个
  async getRepaireList() {
    const res = await wx.http.get('/repairItem')
    this.setData({
      repairList: res.data
    })
  },
  repaireSelect(e) {
    this.setData({
      repairItem: e.detail
    })
  },
  // 时间选择的函数
  datetimeConfirm(e) {
    console.log(e.detail);
    this.setData({
      // 使用dayjs先下包 npm i dayjs  再构建。 在导入就可以使用
      appointment: dayjs(e.detail).format('YYYY-MM-DD'),
      currentDate: e.detail,
      dateLayerVisible: false
    })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openRepairLayer() {
    this.setData({ repairLayerVisible: true })
  },
  closeRepairLayer() {
    this.setData({
      repairLayerVisible: false,
    })
  },

  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  async goList() {
    // 在这里发请求提交报修，和跳转页面之前 先校验，再去做
    if(!this.validateHouse() || !this.validateRepaire() || !this.validateMobile() || !this.validateAppointment() || !this.validateDescription() || !this.validateAttachment()) {
      return
    }
    let tmp = {
      houseId: this.data.houseItem.id,
      repairItemId : this.data.repairItem.id,
      mobile: this.data.mobile,
      appointment: this.data.appointment,
      description: this.data.description,
      attachment: this.data.attachment
    }
    if(this.data.id) {
      // 如果是编辑状态，那么就多添加一个参数，id
      tmp = {...tmp, id: this.data.id}
    }
    // 发请求
    const res = await wx.http.post('/repair', tmp)
    if(res.code !== 10000) {
      wx.utils.toast(res.message || '提交报修失败')
      return
    }
    wx.reLaunch({
      url: '/repair_pkg/pages/list/index',
    })
  },
  afterRead(e) {
    console.log(e.detail.file);
    // 我们在写浏览器里面上传图片的时候，
    // const formData = new FormDate()
    // formData.append('file', e.detail.file.url)
    wx.uploadFile({
      filePath: e.detail.file.url,
      name: 'file',
      url: 'https://live-api.itheima.net/upload',
      header: {
        Authorization: getApp().token
      },
      success: (res) => {
        console.log(res);
        const data = JSON.parse(res.data)
        this.data.attachment.push({url: data.data.url})
        this.setData({
          attachment: this.data.attachment
        })
      }
    })
  },
  deleteImage(e) {
    console.log(e);
    // 先删除本地js数据，在更新页面，小程序比vue多一个步骤
    this.data.attachment.splice(e.detail.index, 1)
    this.setData({
      attachment: this.data.attachment
    })
  },
  // 以下5个函数都是校验相关
  validateHouse() {
    if(!this.data.houseItem.id) {
      wx.utils.toast('必须选择报修房屋')
      return false
    }
    return true
  },
  validateRepaire() {
    if(!this.data.repairItem.id) {
      wx.utils.toast('必须选择维修项目')
      return false
    }
    return true
  },
  validateMobile() {
    const patterrn = /^1[3-9]\d{9}$/
    if(!patterrn.test(this.data.mobile)) {
      wx.utils.toast('手机号格式不对')
      return false
    }
    return true
  },
  validateAppointment() {
    if(!this.data.appointment) {
      wx.utils.toast('预约日期必填')
      return false
    }
    return true
  },
  validateDescription() {
    if(!this.data.description) {
      wx.utils.toast('问题描述必填')
      return false
    }
    if(this.data.description.length > 200) {
      wx.utils.toast('问题描述字数不能大于200')
      return false
    }
    return true
  },
  validateAttachment() {
    if(this.data.attachment.length > 9) {
      wx.utils.toast('问题附件最多传递9个图片')
      return false
    }
    return true
  }
})
